package controllers

import (
	"github.com/astaxie/beego"
	"html/template"
	"src/gitee.com/wx_e6924dbcd0/notebook/models"
	"strconv"
)

type TmbMainController struct {
	beego.Controller
}

/**
 * 获取点赞列表
 */
//http://127.0.0.1:8080/tmblist
func (c *TmbMainController) TmbList() {
	//获取点赞列表
	result := make(map[string]interface{})
	thumbupList, err := models.GetThumbList()
	if err != nil {
		log := models.UitlLog()
		log.Error("GetThumbList failed", err.Error())
		return
	}
	result["thumbupList"] = thumbupList
	c.Data["json"] = result
	c.ServeJSON()
	return
}

/**
 * 点赞
 */
//http://127.0.0.1:8080/tmbu?user_id=2&message_id=3
func (c *TmbMainController) TmbUp() {
	u_id := template.HTMLEscapeString(c.Input().Get("user_id"))
	m_id := template.HTMLEscapeString(c.Input().Get("message_id"))
	user_id, erru := strconv.Atoi(u_id)
	if erru != nil {
		log := models.UitlLog()
		log.Error("string 转int64 err", erru.Error())
		return
	}
	message_id, errm := strconv.Atoi(m_id)
	if errm != nil {
		log := models.UitlLog()
		log.Error("string 转int64 err", errm.Error())
		return
	}
	result := make(map[string]interface{})
	// orm insert 存储
	id, err := models.ThumbU(int64(user_id), int64(message_id))
	if err != nil {
		result["TmbUp"] = "ThumbU failed" + err.Error()
		log := models.UitlLog()
		log.Error("ThumbU err", err.Error())
		return
	} else {
		result["id"] = id
	}

	c.Data["json"] = result
	c.ServeJSON()
	return
}

/**
 * 根据ID取消点赞
 */
//http://127.0.0.1:8080/deltmb?user_id=1&message_id=7
func (c *TmbMainController) DelTmb() {
	// 读取数据库内容
	// 引用model,->orm
	// orm -> 引用 conf 配置连接DB
	// orm 读取数据库
	u_id := template.HTMLEscapeString(c.Input().Get("user_id"))
	m_id := template.HTMLEscapeString(c.Input().Get("message_id"))
	user_id, erru := strconv.Atoi(u_id)
	if erru != nil {
		log := models.UitlLog()
		log.Error("string 转int64 err", erru.Error())
		return
	}
	message_id, errm := strconv.Atoi(m_id)
	if errm != nil {
		log := models.UitlLog()
		log.Error("string 转int64 err", errm.Error())
		return
	}
	result := make(map[string]interface{})
	//执行删除操作
	num, err := models.DelThumb(int64(user_id), int64(message_id))
	if err != nil {
		result["count"] = num
		result["DelTmb"] = "DelThumb failed" + err.Error()
		log := models.UitlLog()
		log.Error("DelThumb err", err.Error())
		return
	}
	// 成功返回数据
	result["count"] = num
	result["DelTmb"] = "ok"
	c.Data["json"] = result
	c.ServeJSON()
}
